package com.freight.message.config;

import com.freight.common.core.constant.WebsocketConstants;
import com.freight.message.interceptor.WsUserChannelInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * websocket配置类
 *    @EnableWebSocketMessageBroker: 开启websocket的子协议STOMP
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册 STOMP的 endpoint，前端建立 socket连接时的 url
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 客户端向服务端发起请求时，需要以/app为前缀，并将被路由到 @RestController类的 @MessageMapping()方法
        registry.setApplicationDestinationPrefixes(WebsocketConstants.DESTINATION_PRE_APP);

        // 表明在 topic、user这几个域上可以向客户端发消息：topic用来广播，user用来实现点对点
        registry.enableSimpleBroker(WebsocketConstants.SUBSCRIBE_PRE_TOPIC, WebsocketConstants.SUBSCRIBE_PRE_USER);

        // 点对点发送的前缀
        registry.setUserDestinationPrefix(WebsocketConstants.SUBSCRIBE_PRE_USER);
    }

    /**
     * 用户入端通道拦截器
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new WsUserChannelInterceptor());
    }

}
